package ejb.cbm.admin.session;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;

import ejb.cbm.admin.bean.ParametroBean;
import ejb.cbm.admin.entity.ParametroEntity;
import ejb.cbm.admin.local.ParametroSessionLocal;

////@Stateless
@Service("parametroSessionLocal")
public class ParametroSession extends HibernateDaoSupport implements ParametroSessionLocal {
	
	static Logger logger = Logger.getLogger(ParametroSession.class.getName());
	//property constants
	public static final String DESCRIPCION = "descripcion";
	public static final String VALORNUMERICO = "valornumerico";
	public static final String VALORALFANUMERICO = "valoralfanumerico";
	public static final String FLAGACTIVO = "flagactivo";
	public static final String USUARIOREGISTRO = "usuarioregistro";
	public static final String USUARIOMODIFICACION = "usuariomodificacion";


    //@PersistenceContext 
    //private EntityManager entityManager;
	@Autowired
	public ParametroSession(SessionFactory sessionFactory){
		super.setSessionFactory(sessionFactory);
	}
	
    public void save(ParametroEntity transientInstance) {
    	logger.log("saving ParametroEntity instance", Level.INFO, null,null);
        try {
            getSession().persist(transientInstance);
            logger.log("save successful", Level.INFO, null,null);
        } catch (RuntimeException re) {
        	logger.log("save failed", Level.FATAL,null, re);
            throw re;
        }
    }
    
    public void delete(ParametroEntity persistentInstance) {
    	logger.log("deleting ParametroEntity instance", Level.INFO, null,null);
        try {
            getSession().delete(persistentInstance);
            logger.log("delete successful", Level.INFO, null,null);
        } catch (RuntimeException re) {
        	logger.log("delete failed", Level.FATAL,null, re);
            throw re;
        }
    }
    
    public ParametroEntity update(ParametroEntity detachedInstance) {
    	logger.log("updating ParametroEntity instance", Level.INFO, null,null);
        try {
            ParametroEntity result = (ParametroEntity) getSession().merge(detachedInstance);
            logger.log("update successful", Level.INFO, null,null);
            return result;
        } catch (RuntimeException re) {
        	logger.log("update failed", Level.FATAL,null, re);
            throw re;
        }
    }
    
    public ParametroEntity findById( Long id) {
    	logger.log("finding ParametroEntity instance with id: " + id, Level.INFO,null, null);
        try {
            ParametroEntity instance = (ParametroEntity) getSession().get(ParametroEntity.class, id);
            return instance;
        } catch (RuntimeException re) {
        	logger.log("find failed", Level.FATAL,null, re);
            throw re;
        }
    }
    
    //@SuppressWarnings("unchecked")
    public List<ParametroEntity> findByProperty(String propertyName, Object value) {
    	logger.log("finding ParametroEntity instance with property: " + propertyName
    						+ ", value: " + value, Level.INFO, null,null);
		try {
			String queryString = "select model from ParametroEntity model where model." 
			 						+ propertyName + "= :propertyValue";
			return getSession().createQuery(queryString)
 				.setParameter("propertyValue", value).list();
		} catch (RuntimeException re) {
			logger.log("find by property name failed", Level.FATAL,null, re);
			throw re;
		}
	}
    
    public List<ParametroEntity> findByCodigoTipoParametro(Object value) {    	
		try {
			String queryString = "select model from ParametroEntity model where model.tipoparametro.codigotipoparametro" 
			 						+"= :propertyValue";
			return getSession().createQuery(queryString)
 				.setParameter("propertyValue", value).list();
		} catch (RuntimeException re) {
			logger.log("find by property name failed", Level.FATAL,null, re);
			throw re;
		}
	}
    
    
    
    //@SuppressWarnings("unchecked")
	public ParametroEntity findParametro(Long codigoTipo, Double valorParametro){
		logger.log("findByFiltro RegistroIngresoEntity instance", Level.INFO, null, null);
		StringBuilder query = new StringBuilder();
		ParametroEntity entity = new ParametroEntity();
		List<ParametroEntity> lstParametros = null;
		try{
			query.append("select model  ");
			query.append("from ParametroEntity model ");
			query.append("where model.tipoparametro.codigotipoparametro = :codigoTipo");
			
			if (valorParametro != null)
				query.append(" and model.valornumerico = :valor ");
				
			
			if (valorParametro == null){
				entity = (ParametroEntity)getSession().createQuery(query.toString()).
					setParameter("codigoTipo", codigoTipo).list();
			}else{
				lstParametros = getSession().createQuery(query.toString()).
				setParameter("codigoTipo", codigoTipo).
				setParameter("valor", valorParametro).list();
				
				for(ParametroEntity parametro: lstParametros){
					entity = parametro;
				}
			}
			
			return entity;
		}catch(RuntimeException e){
			e.printStackTrace();
			logger.log("findLast failed", Level.FATAL, null, e);
			throw e;
		}
	}
	
	public List<ParametroEntity> findByDescripcion(Object descripcion) {
		return findByProperty(DESCRIPCION, descripcion);
	}
	
	public List<ParametroEntity> findByValornumerico(Object valornumerico) {
		return findByProperty(VALORNUMERICO, valornumerico);
	}
	
	public List<ParametroEntity> findByValoralfanumerico(Object valoralfanumerico) {
		return findByProperty(VALORALFANUMERICO, valoralfanumerico);
	}
	
	public List<ParametroEntity> findByFlagactivo(Object flagactivo) {
		return findByProperty(FLAGACTIVO, flagactivo);
	}
	
	public List<ParametroEntity> findByUsuarioregistro(Object usuarioregistro) {
		return findByProperty(USUARIOREGISTRO, usuarioregistro);
	}
	
	public List<ParametroEntity> findByUsuariomodificacion(Object usuariomodificacion) {
		return findByProperty(USUARIOMODIFICACION, usuariomodificacion);
	}

	//gclv 16/09/2011
	//@SuppressWarnings("unchecked")
	public List<ParametroEntity> findByFiltro(ParametroBean filtro){
		logger.log("findByFiltro ParametroEntity instance", Level.INFO, null, null);
		StringBuilder query = new StringBuilder();
		
		try{
			query.append("select model ");
			query.append("from  ParametroEntity model ");
			query.append("where 1 = 1 ");
			
			if (filtro.getCodigoparametro()!=null){
				query.append(" and model.codigoparametro = "+filtro.getCodigoparametro());
			}
			if (filtro.getFlagactivo()!=null){
				query.append(" and model.flagactivo = "+filtro.getFlagactivo());
			}
			if (filtro.getDescripcion()!=null){
				query.append(" and model.descripcion = '"+filtro.getDescripcion()+"'");
			}
			if (filtro.getValornumerico()!=null){
				query.append(" and model.valornumerico = "+filtro.getValornumerico());
			}
			if (filtro.getValoralfanumerico()!=null){
				query.append(" and model.valoralfanumerico = '"+filtro.getValoralfanumerico()+"'");
			}
			
			query.append(" order by model.codigoparametro ");
			
			return getSession().createQuery(query.toString()).list();
			
		}catch(RuntimeException e){
			logger.log("findByFiltro failed", Level.FATAL, null, e);
			throw e;
		}
	}	

	//@SuppressWarnings("unchecked")
	public List<ParametroEntity> findAll() {
		logger.log("finding all ParametroEntity instances", Level.INFO, null,null);
		try {
			String queryString = "select model from ParametroEntity model";
			return getSession().createQuery(queryString).list();
		} catch (RuntimeException re) {
			logger.log("find all failed", Level.FATAL,null, re);
			throw re;
		}
	}
}